﻿#region Using
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
#endregion Using

namespace LloydGame
{
    class ScreenQuickMatch : GameScreen
    {

        #region Fields
        protected AvailableNetworkSessionCollection m_available_sessions;
        protected NetworkSession m_network_session;
        protected bool m_search_started = false;
        protected bool m_session_found = false;
        #endregion Fields

        #region Constructor
        public ScreenQuickMatch(Game p_game, GameScreen p_owner)
            : base(p_game, "Quick Match")
        {

            m_network_session = ((Game1)p_game).networkSession;
            m_ownerscreen = p_owner;
            m_slide_x = 0;

            // Network must be not initiated
            /*if (m_network_session == null)
            {
                Console.WriteLine("Network error: NetworkSession is not null when QuickMatch started.");
                Close();
            }*/

        }
        #endregion Constructor

        #region Update
        public override void Update(GameTime p_gametime)
        {
            base.Update(p_gametime);

            if (!m_rendersubscreen)
            {

                // Init search!
                if (Gamer.SignedInGamers.Count == 0)
                {
                    // If there are no profiles signed in, we cannot proceed.
                    // Show the Guide so the user can sign in, and close this screen!
                    Guide.ShowSignIn(1, false);
                    if (m_ownerscreen.GetType().ToString() == "LloydGame.ScreenMultiplayer")
                        ((ScreenMultiplayer)m_ownerscreen).lasterror = "Please sign in and try again!";
                    Close();
                }
                // Quick hack for easy multiplayer debug
                else if (m_ownerscreen.GetType().ToString() != "LloydGame.ScreenMultiplayer")
                {
                    // Create new session!
                    try
                    {
                        m_available_sessions = null;
                        ((Game1)m_game).networkSession = NetworkSession.Create(NetworkSessionType.SystemLink,
                                                               1, ((Game1)m_game).networkMaxPlayers);
                        Console.WriteLine("New network session created!");
                        m_ownerscreen.StartSubscreen(new ScreenLobby(m_game, m_ownerscreen, MultiplayerType.SystemLink));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Close();
                    }
                }
                else if (!m_search_started)
                {
                    m_search_started = true;

                    // Initiate search!
                    try
                    {

                        // Search for sessions.
                        using (m_available_sessions = NetworkSession.Find(NetworkSessionType.SystemLink,
                                                        1, null))
                        {

                            if (m_available_sessions.Count == 0)
                            {
                                m_session_found = false;
                                Console.WriteLine("No network sessions found.");
                            }
                            else
                            {
                                m_session_found = true;
                                Console.WriteLine("Sessions found!");

                                try
                                {
                                    // Join the first session we found.
                                    ((Game1)m_game).networkSession = NetworkSession.Join(m_available_sessions[0]);

                                    Console.WriteLine("Joined first session we found!");
                                    m_ownerscreen.StartSubscreen(new ScreenLobby(m_game, m_ownerscreen, MultiplayerType.SystemLink));
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                    ((ScreenMultiplayer)m_ownerscreen).lasterror = "Error:\n" + e.Message;
                                    Close();
                                }
                            }

                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        ((ScreenMultiplayer)m_ownerscreen).lasterror = "Error:\n" + e.Message;
                        Close();
                    }
                }
                else
                {
                    if (!m_session_found)
                    {
                        // Create new session!
                        try
                        {
                            m_available_sessions = null;
                            ((Game1)m_game).networkSession = NetworkSession.Create(NetworkSessionType.SystemLink,
                                                                   1, ((Game1)m_game).networkMaxPlayers);
                            Console.WriteLine("New network session created!");
                            m_ownerscreen.StartSubscreen(new ScreenLobby(m_game, m_ownerscreen, MultiplayerType.SystemLink));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                            ((ScreenMultiplayer)m_ownerscreen).lasterror = "Error:\n" + e.Message;
                            Close();
                        }
                    }
                }

            }

            // Store keyboard and mouse states
            StoreStates();
        }
        #endregion Update

        #region Draw
        public override void Draw()
        {
            m_screenmatrix = Matrix.CreateTranslation(m_slide_x, 0, 0);
            m_spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.None, m_screenmatrix);

            m_spriteBatch.DrawString(m_normalfont, "Searching for a match...", new Vector2(80 + 1, 100 + 1), Color.Black);
            m_spriteBatch.DrawString(m_normalfont, "Searching for a match...", new Vector2(80, 100), Color.White);

            // Draw menu components
            //foreach (GameScreenComponent t_component in m_selectable_components)
            //{
            //    t_component.Draw(m_spriteBatch, false);
            //}

            m_spriteBatch.End();
            base.Draw();
        }
        #endregion Draw

    }
}
